package cc.site.main.controller;

import cc.site.common.utils.R;
import cc.site.main.bean.TblUser;
import cc.site.main.bean.dto.PetDto;
import cc.site.main.bean.vo.UserVo;
import cc.site.main.service.TblPetService;
import cc.site.main.service.TblUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yangruomao
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class TblUserController {

    @Autowired
    private  TblUserService userService;

    @Autowired
    private TblPetService petService;

    @DeleteMapping
    @ApiOperation("删除用户")
    public R delete(@RequestParam("id") Integer id) {
        userService.removeById(id);
        return R.ok().message("删除成功");
    }

    @PutMapping
    @ApiOperation("编辑用户")
    public R update(Integer userId ,@Valid @RequestBody(required = false) UserVo vo) {

        // 检查账号是否重复
        LambdaQueryWrapper<TblUser> w = new LambdaQueryWrapper<TblUser>();
        w.eq(TblUser::getUsername, vo.getUsername());
        if (userService.count(w) > 0) {
            return R.error().message("用户名已存在");
        }

        // 编辑用户
        TblUser user = userService.getById(userId);
        if (user == null) return R.error().message("用户不存在");
        BeanUtils.copyProperties(vo, user);
        userService.updateById(user);

        return R.ok().message("编辑成功");
    }

    @GetMapping("/{page}/{limit}")
    @ApiOperation("分页获取用户数据，page从1开始")
    public R list(@PathVariable("page") Integer page, @PathVariable("limit") Integer limit) {
        // 查出 user 表所有数据
        Page<TblUser> res = userService.page(new Page<>(page, limit), null);
        return R.ok().data("page", res);
    }

}
